#include <math.h>
#include <pspdebug.h>
#include <pspdisplay.h>
#include <pspkernel.h>
#include <pspgu.h>
#include <pspgum.h>
#include "../Common/Callbacks.h"
#include "../Epik_Controller.h"
#include "../Epik_Movement.h"
#include "../Epik_Model.h"

PSP_MODULE_INFO("Epik_Model DEMO", 0, 1, 1);
unsigned int __attribute__((aligned(16))) _list[262144];

void SetupFrame();
void SetupGU();

int main()
{
	SetupCallbacks();
	SetupGU();
	pspDebugScreenInit();

	int val = 0;
	bool btnX;
	bool btnSTART;
	Epik_Model *map = new Epik_Model("Map1.em");
	Epik_Model *person = new Epik_Model("Polygon.em");

	sceKernelDelayThread(7500000);

	Epik_Controller *ec = new Epik_Controller(&_running, 15000);
	ec->BindButton(Epik_Controller::BTN_CROSS, &btnX);
	ec->BindButton(Epik_Controller::HUB_START, &btnSTART);

	while(_running)
	{
		ec->UpdateButtons();
		SetupFrame();

		{
			ScePspFVector3 pos = { 0.0f, -1.0f,-5.0f};
			sceGumTranslate(&pos);
			map->Render();
		}/*{
			ScePspFVector3 rot = { val*0.79f*(M_PI/180.0f), 0, 0};
			sceGumRotateXYZ(&rot);
		}*/{
			sceGumLoadIdentity();
			ScePspFVector3 pos = { 0.0f, 1.0f, -5.0f };
			sceGumTranslate(&pos);
			person->Render();
		}

		pspDebugScreenSetXY(0,0);
		pspDebugScreenPrintf("press X to move the arms.");

		sceGuFinish();
		sceGuSync(0, 0);
		val++;

		if (btnX)
			person->SetMove(0);
		if (btnSTART)
			_running = false;

		sceDisplayWaitVblankStart();
		sceGuSwapBuffers();
	}

	sceKernelExitGame();
}

void SetupFrame()
{
	sceGuStart(GU_DIRECT, _list);

	sceGuClearColor(0xFF554433);
	sceGuClearDepth(0);
	sceGuClear(GU_COLOR_BUFFER_BIT | GU_DEPTH_BUFFER_BIT);

	sceGumMatrixMode(GU_PROJECTION);
	sceGumLoadIdentity();
	sceGumPerspective(75.0f, 16.0f/9.0f, 0.5f, 1000.0f);

	sceGumMatrixMode(GU_VIEW);
	{
		sceGumLoadIdentity();
		ScePspFVector3 eye = {3.0f, 5.0f, 5.0f};
		ScePspFVector3 pos = {0.0f, 1.0f, -5.0f};
		ScePspFVector3 top = {0.0f, 1.0f, 0.0f};

		sceGumLookAt(&eye, &pos, &top);
	}

	sceGumMatrixMode(GU_MODEL);
	sceGumLoadIdentity();
}

void SetupGU()
{
	sceGuInit();

	sceGuStart(GU_DIRECT, _list);
	sceGuDrawBuffer(GU_PSM_8888, (void *)0, 512);
	sceGuDispBuffer(480, 272, (void *)0x88000, 512);
	sceGuDepthBuffer((void *)0x110000, 512);
	sceGuOffset(2048 - (480/2), 2048 - (272/2));
	sceGuViewport(2048, 2048, 480, 272);
	sceGuDepthRange(0xC350, 0x2710);
	sceGuScissor(0, 0, 480, 272);
	sceGuEnable(GU_SCISSOR_TEST);
	sceGuDepthFunc(GU_GEQUAL);
	sceGuEnable(GU_DEPTH_TEST);
	sceGuFrontFace(GU_CW);
	sceGuShadeModel(GU_SMOOTH);
	sceGuEnable(GU_CULL_FACE);
	sceGuEnable(GU_CLIP_PLANES);
	sceGuFinish();
	sceGuSync(0, 0);

	// Wait for GU to finish saving/Rendering
	sceDisplayWaitVblankStart();
	// Turn on the screen
	sceGuDisplay(GU_TRUE);
}


